package com.song.article.controller;

import com.song.api.BaseController;
import com.song.api.controller.article.CommentControllerApi;
import com.song.api.controller.user.UserControllerApi;
import com.song.article.service.CommentPortalService;
import com.song.grace.result.GraceJSONResult;
import com.song.grace.result.ResponseStatusEnum;
import com.song.pojo.bo.CommentReplyBO;
import com.song.pojo.vo.AppUserVO;
import com.song.utils.JsonUtils;
import com.song.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
public class CommentController extends BaseController implements CommentControllerApi {

    private static final Logger LOG = LoggerFactory.getLogger(CommentController.class);

    @Autowired
    private CommentPortalService commentPortalService;

    // 注入服务发现，可以获得已注册的服务相关信息
    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public GraceJSONResult createComment(@Valid CommentReplyBO commentReplyBO) {

        // 1.根据留言用户id查询他的昵称，用于冗余存入留言记录，避免多表管理查询的性能开支
        String userId = commentReplyBO.getCommentUserId();

        // 2.获得用户基本信息
        Set<String> idSet = new HashSet<>();
        idSet.add(userId);
        // 发起远程调用，获得用户基本信息
        AppUserVO userVO = getPublisherList(idSet).get(0);
        String nickname = userVO.getNickname();
        String commentUserFace = userVO.getFace();

        // 3.保存评论信息
        commentPortalService.createComment(commentReplyBO.getArticleId(),
                commentReplyBO.getFatherId(),
                userId,
                commentReplyBO.getContent(),
                nickname,
                commentUserFace);
        return GraceJSONResult.ok();
    }

    @Autowired
    private UserControllerApi userControllerApi;

    /**
     * 发起远程调用，请求用户服务获得用户基本信息（idSet 发布者）的列表
     *
     * @param idSet
     * @return
     */
    public List<AppUserVO> getPublisherList(Set idSet) {
//        String serviceId = "SERVICE-USER";
//        String url
//                = "http://"
//                + serviceId
//                + "/user/queryByIds?userIds="
//                + JsonUtils.objectToJson(idSet);
//
//        ResponseEntity<GraceJSONResult> responseEntity
//                = restTemplate.getForEntity(url, GraceJSONResult.class);
//        GraceJSONResult bodyResult = responseEntity.getBody();
        GraceJSONResult bodyResult = userControllerApi.queryByIds(JsonUtils.objectToJson(idSet));
        List<AppUserVO> publisherList = null;
        if (bodyResult.getStatus() == 200) {
            String userJson = JsonUtils.objectToJson(bodyResult.getData());
            publisherList = JsonUtils.jsonToList(userJson, AppUserVO.class);
        } else {
            publisherList = new ArrayList<>();
        }
        return publisherList;
    }

    @Override
    public GraceJSONResult counts(String articleId) {

		// 0.参数判空
		if (StringUtils.isBlank(articleId)){
		    return GraceJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_REQUEST_PARAMETER_ERROR);
		}
		
        Integer counts = getCountsFromRedis(REDIS_ARTICLE_COMMENT_COUNTS + articleId);

        return GraceJSONResult.ok(counts);
    }

    @Override
    public GraceJSONResult list(String articleId, Integer page, Integer pageSize) {
		
		// 0.参数判空
		if (StringUtils.isBlank(articleId)){
		    return GraceJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_REQUEST_PARAMETER_ERROR);
		}
		
        if (page == null) {
            page = COMMON_START_PAGE;
        }

        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }

        PagedGridResult gridResult = commentPortalService.queryArticleComments(articleId, page, pageSize);

        return GraceJSONResult.ok(gridResult);
    }

    @Override
    public GraceJSONResult mng(String writerId, Integer page, Integer pageSize) {

		// 0.参数判空
        if (StringUtils.isBlank(writerId)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_REQUEST_PARAMETER_ERROR);
        }
		
        if (page == null) {
            page = COMMON_START_PAGE;
        }

        if (pageSize == null) {
            pageSize = COMMON_PAGE_SIZE;
        }

        PagedGridResult gridResult = commentPortalService.queryWriterCommentsMng(writerId, page, pageSize);

        return GraceJSONResult.ok(gridResult);
    }

    @Override
    public GraceJSONResult delete(String writerId, String commentId) {
		
        // 0.参数判空
        if (StringUtils.isBlank(writerId)||StringUtils.isBlank(commentId)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SYSTEM_REQUEST_PARAMETER_ERROR);
        }

        commentPortalService.deleteComment(writerId,commentId);

        return GraceJSONResult.ok();
    }

}
